<template>
  <div class="select-field">
    <el-form ref="formDataRef" :model="dataForm" :rules="formRules" label-position="right" label-width="85px">
      <el-form-item
        prop="fieldName"
        label="选取字段"
        class="is-required">
        <!-- 关联字段 -->
        <div class="filter-item">
          <el-input v-model="mustField.columnName" maxlength="20" class="input-container" placeholder="请输入列名称" size="small" type="text" />
          <el-select
            v-model="mustField.fieldCategorys"
            class="width120"
            name="field"
            size="small"
            style="margin-right: 12px"
            popper-class="global-select-down"
            @change="selectFieldCategorys($event, mustField)">
            <el-option
              :value="''"
              label="请选择" />
            <el-option
              v-for="item in mustFieldList"
              :key="item.id"
              :label="item.name"
              :value="item.id" />
          </el-select>
          <el-select v-model="mustField.fieldId" size="small" name="field" class="width120" popper-class="global-select-down" @change="selectField($event, mustField)">
            <el-option
              :value="''"
              label="请选择" />
            <el-option
              v-for="item in mustField.fieldChidrenList"
              :key="item.id"
              :label="item.name"
              :value="item.id" />
          </el-select>
          <div class="mustField-item tool-bar">
            <el-tooltip :content="`隐藏标签:${mustField.hideTag === 1?'隐藏':'显示'}`" placement="top">
              <i :style="mustField.hideTag === 1?{color: '#999'}:{color: '#406eff'}" class="eye-icon el-icon-view" @click="changemustFieldHide"/>
            </el-tooltip>
            <el-tooltip :content="'设为唯一值：不可取消'" placement="top">
              <i :style="mustField.uniqueFlag === 1?{color: '#406eff'}:{color: '#999'}" class="eye-icon el-icon-key"/>
            </el-tooltip>
          </div>
        </div>
        <!-- 普通字段 -->
        <div
          v-for="(item, index) in fields"
          :key="index"
          class="filter-item">
          <template v-if="!item.fieldType">
            <el-input v-model="item.columnName" class="input-container" maxlength="20" placeholder="请输入列名称" size="small" type="text" />
            <el-select v-model="item.fieldCategorys" size="small" class="width120" name="field" popper-class="global-select-down" style="margin-right: 12px" @change="selectFieldCategorys($event, item)">
              <el-option :value="''" label="请选择" />
              <template v-for="item in fieldList">
                <el-option
                  v-if="item.name !== '关联字段' && item.name !== '统计报表'"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id" />
              </template>
              <el-option
                :key="-1"
                :label="'统计报表'"
                :value="-1" />
            </el-select>
            <!-- 选择报表 -->
            <template v-if="isReportField(item.fieldCategorys)">
              <selectWithUserLoad
                v-model="item.reportId"
                :loadmore-method="getRemoteReport()"
                placeholder="请选择报表"
                key-name="id"
                label-name="name"
                extend-class="select-report"
                class="width120"
                filterable
                style="margin-right:10px;"
                collapse-tags
                clearable
                @change="getReportFieldFun($event, item, true)"
              />
            </template>
            <el-select v-model="item.fieldId" size="small" name="field" class="width120" popper-class="global-select-down" @change="selectField($event, item)">
              <el-option
                :value="''"
                label="请选择" />
              <el-option
                v-for="item in item.fieldChidrenList"
                :key="item.id"
                :label="item.name"
                :value="item.id" />
            </el-select>
            <span class="tip-word">的</span>
            <el-select v-model="item.filedFormula" size="small" popper-class="global-select-down" class="width120" name="field">
              <el-option
                :value="''"
                label="请选择" />
              <el-option
                v-for="item in filedFormulaOpt"
                :key="item"
                :label="item"
                :value="item" />
            </el-select>
          </template>
          <div v-else>
            <!-- 公式字段 -->
            <div style="margin-bottom:10px;">
              <el-input v-model="item.columnName" class="input-container" maxlength="20" placeholder="请输入列名称" size="small" type="text" />
            </div>
            <div class="formula-container">
              <OverviewFormula v-model="item.formulaOrigin" :tags-options="handelData(fields)" quote-label-placeholder="请选择引用的列" value-key="columnName" quote-label-name="引用列" />
              <div style="display:flex;align-items:center;">
                <div style="color:#606266;width:85px;text-align:right;padding-right:10px;">单位</div>
                <el-input v-model="item.unit" size="small" style="width:240px;" placeholder="不超过10个字符" maxlength="10" />
              </div>
            </div>
          </div>
          <!-- <div v-if="index === 0" class="add-btn" @click="addItem">
            <img :src="addIcon" alt="">
          </div> -->
          <div :class="{'float': item.fieldType}" class="tool-bar">
            <div class="delete-btn" @click="deleteItem(index)">
              <i class="delete-icon el-icon-delete" />
            </div>
            <!-- 向上 -->
            <el-tooltip content="往前移" placement="top">
              <i v-if="index !== 0" class="index-icon el-icon-top" @click="changeIndex('top',index)"/>
              <i v-else class="index-icon el-icon-top" style="color:#999;cursor:not-allowed;" />
            </el-tooltip>
            <!-- 向下 -->
            <el-tooltip content="往后移" placement="top">
              <i v-if="index !== fields.length-1" class="index-icon el-icon-bottom" @click="changeIndex('bottom',index)"/>
              <i v-else class="index-icon el-icon-bottom" style="color:#999;cursor:not-allowed;" />
            </el-tooltip>
            <!-- 复制 -->
            <el-tooltip content="复制" placement="top">
              <i class="index-icon el-icon-copy-document" @click="copyTag(item)" />
            </el-tooltip>
            <!-- 隐藏标签 -->
            <el-tooltip :content="`隐藏标签:${item.hideTag === 1?'隐藏':'显示'}`" placement="top">
              <i :style="item.hideTag === 1?{color: '#999'}:{color: '#406eff'}" class="eye-icon el-icon-view" @click="changeHideTag(item)"/>
            </el-tooltip>
            <el-tooltip :content="'设为唯一值'" placement="top">
              <i :style="item.uniqueFlag === 1?{color: '#406eff'}:{color: '#999'}" class="eye-icon el-icon-key" @click="changeUniqueFlag(item)"/>
            </el-tooltip>
            <!-- <i :style="item.uniqueFlag === 1?{color: '#406eff'}:{color: '#999'}" class="eye-icon el-icon-s-flag" @click="changeUniqueFlag(item)"/> -->
          </div>
        </div>
        <div>
          <!-- <el-button type="primary" size="small" @click="addItem(0)">添加列</el-button>
          <el-button type="primary" size="small" @click="addItem(1)">添加公式列</el-button> -->
          <PlainCreateBtn size="small" @click="addItem(0)">添加列</PlainCreateBtn>
          <PlainCreateBtn size="small" @click="addItem(1)">添加公式列</PlainCreateBtn>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { getFieldList, getOptions, getReportList, getReportField } from '@/api/reportManage';
import addIcon from '@/assets/reportManage/add_icon.png';
import { mapState } from 'vuex';
import ElMessage from '@/utils/message';
import OverviewFormula from './module/overviewFormula';
import selectWithUserLoad from '@/components/Common/selectWithUserLoad';

export default {
  name: 'SelectField',
  components: { OverviewFormula, selectWithUserLoad },
  data() {
    return {
      addIcon,
      dataForm: {},
      formRules: {},
      systemWord: ['系统字段'], // 系统字段
      filedFormulaOpt: ['求和', '平均数', '计数', '计数(去重)', '求和-同比', '求和-环比', '计数-同比', '计数(去重)-同比', '计数-环比', '计数(去重)-环比'],
      fields: [
        {
          columnName: '',
          fieldType: 0,
          fieldId: '',
          reportId: '',
          filedFormula: '',
          fieldName: '',
          fieldCategorysName: '',
          fieldCategorys: '',
          hideTag: 0,
          uniqueFlag: 0
        }
      ],
      mustField: {
        columnName: '',
        fieldType: 0,
        fieldId: '',
        reportId: '',
        filedFormula: '',
        fieldName: '',
        fieldCategorysName: '关联字段',
        fieldCategorys: '',
        hideTag: 0,
        uniqueFlag: 1
      },
      mustFieldList: [],
      conditionOptions: [],
      mathOperationOptions: []
    };
  },
  computed: {
    ...mapState({
      'fieldList': state => state.options.fieldList,
      'collectOptions': state => state.options.collectOptions
    })
  },
  created() {
    this.getOpt();
    if (this.fieldList.length <= 0 || this.fieldList[0].name !== '关联字段') {
      this.getField();
    } else {
      this.fieldList.forEach(i => {
        if (i.name === '关联字段') {
          this.mustFieldList = [i];
          this.mustField.fieldCategorys = i.id;
          this.mustField.fieldChidrenList = i.fieldInfo;
        }
      });
    }
  },
  methods: {
    setDefaultField(dataForm) {
      this.callback = function() {
        const data = JSON.parse(JSON.stringify(dataForm));
        let mustField;
        this.fieldList.forEach(i => {
          if (i.name === '关联字段') {
            mustField = i;
          }
        });
        // const report = this.fieldList.find(i => i.name === '统计报表');
        data.forEach(k => {
          k.filedFormula = k.formula;
          // 统计报表单独处理
          if (k.reportId) {
            k.fieldCategorys = -1;
            k.fieldCategorysName = '统计报表';
            this.getReportFieldFun(k.reportId, k);
          } else {
            this.fieldList.forEach(i => {
              i.fieldInfo.forEach(j => {
                if (Number(j.id) === Number(k.fieldId)) {
                  k.fieldCategorys = i.id;
                  k.fieldChidrenList = i.fieldInfo;
                  k.fieldCategorysName = i.name;
                }
              });
            });
          }

          if (k.fieldCategorys === mustField.id) {
            k.isMustfield = true;
            this.mustField = k;
            this.mustField.uniqueFlag = 1;
          }
          if (k.fieldType === 1) {
            if (k.formulaOrigin && k.formulaOrigin !== '') {
              k.formulaOrigin = JSON.parse(k.formulaOrigin);
            }
            // 关联变量对象的指针地址
            if (k.formulaOrigin && k.formulaOrigin.length) {
              for (let j = 0; j < k.formulaOrigin.length; j++) {
                data.forEach(i => {
                  if (!i.fieldType && k.formulaOrigin[j].type === 'var' && i.columnName === k.formulaOrigin[j].columnName) {
                    i.type = 'var';
                    k.formulaOrigin[j] = i;
                  }
                });
              }
            }
          }
        });
        this.fields = data.filter(i => !i.isMustfield);
        if (this.fields.length === 0) {
          this.fields = [{
            fieldId: '',
            filedFormula: '',
            fieldName: '',
            fieldCategorysName: '',
            fieldCategorys: ''
          }];
        }
        this.isSystemWord();
      };
      if (this.fieldList && this.fieldList.length) {
        this.callback();
      }
    },
    isSystemWord() {
      const isSystem = this.fields.some(i => {
        return this.systemWord.includes(i.fieldCategorysName);
      });
      this.$emit('setIsSystem', isSystem);
    },
    async getField(name = '') {
      try {
        const res = await getFieldList({ name, use: 2 });
        if (res.data) {
          res.data.forEach(i => {
            if (i.name === '关联字段') {
              this.mustFieldList = [i];
              this.mustField.fieldCategorys = i.id;
              this.mustField.fieldChidrenList = i.fieldInfo;
            }
          });
          this.$store.commit('SET_FIELDLIST', res.data);
          if (this.callback) {
            this.callback();
          }
        }
      } catch (error) {
        console.error(error);
      }
    },
    addItem(type = 0) {
      const item = {
        fieldType: type,
        columnName: '',
        fieldId: '',
        filedFormula: '',
        fieldName: '',
        fieldCategorysName: '',
        reportId: '',
        fieldCategorys: '',
        hideTag: 0
      };
      if (type === 1) { // 公式字段
        item.tagFormula = '';
        item.formulaVariable = [];
        item.formulaOrigin = []; // 原数据
        item.unit = '';
      }
      this.fields.push(item);
    },
    deleteItem(index) {
      this.fields.splice(index, 1);
    },
    selectFieldCategorys(id, item) {
      item.reportId = '';
      if (id === '') {
        item.fieldChidrenList = [];
        item.fieldCategorysName = '';
        item.fieldId = '';
        this.isSystemWord();
        return;
      }
      this.fieldList.forEach(i => {
        if (i.id === id) {
          item.fieldChidrenList = i.fieldInfo;
          item.fieldCategorysName = i.name;
        }
      });
      item.fieldId = '';
      this.isSystemWord();
      if (this.isReportField(id)) {
        item.fieldChidrenList = [];
      }
    },
    selectField(id, item) {
      const isReport = this.isReportField(item.fieldCategorys);
      if (isReport) {
        item.fieldChidrenList.forEach(i => {
          if (i.id === id) {
            item.fieldName = i.name;
            item.columnName = i.name;
          }
        });
      } else {
        this.fieldList.forEach(i => {
          i.fieldInfo.forEach(j => {
            if (j.id === id) {
              item.fieldName = j.name;
              item.columnName = item.fieldName;
            }
          });
        });
      }
    },
    // 工具操作
    changemustFieldHide() {
      this.mustField.hideTag = this.mustField.hideTag === 1 ? 0 : 1;
    },
    handelData(fields) {
      const res = fields.filter(i => {
        return !i.fieldType && i.columnName;
      });
      if (this.mustField.columnName) res.unshift(this.mustField);
      return res;
    },
    // 上移下移
    changeIndex(type, index) {
      const arr = this.fields.splice(index, 1);
      if (type === 'bottom') {
        this.fields.splice(index + 1, 0, arr[0]);
      } else if (type === 'top') {
        this.fields.splice(index - 1, 0, arr[0]);
      }
    },
    // 隐藏标签
    changeHideTag(item) {
      item.hideTag = item.hideTag === 1 ? 0 : 1;
    },
    changeUniqueFlag(item) {
      this.$set(item, 'uniqueFlag', item.uniqueFlag === 1 ? 0 : 1);
      // item.uniqueFlag = item.uniqueFlag === 1 ? 0 : 1;
    },
    copyTag(item) {
      let formulaOrigin = [];
      if (item.formulaOrigin && item.formulaOrigin.length) {
        formulaOrigin = [...item.formulaOrigin];
      }
      const tagItem = _.cloneDeep(item);
      tagItem.formulaOrigin = formulaOrigin;

      let index = 0;
      const tagName = `${tagItem.columnName}-副本`;
      this.fields.forEach(i => {
        if (i.columnName.indexOf(tagName) >= 0) {
          index++;
        }
      });
      if (index > 0) {
        tagItem.columnName = tagName + index;
      } else {
        tagItem.columnName = tagName;
      }
      this.fields.push(tagItem);
      ElMessage.success('复制成功');
    },
    // 暴露给父组件获取参数
    getParams() {
      let error = '';
      const mustField = JSON.parse(JSON.stringify(this.mustField));
      const fields = JSON.parse(JSON.stringify(this.fields));
      fields.unshift(mustField);
      const selectFieldParams = fields.map(i => {
        const obj = {
          columnName: i.columnName,
          fieldId: i.fieldId,
          reportId: i.reportId || '',
          fieldName: i.fieldName,
          formula: i.filedFormula || '',
          fieldType: i.fieldType || 0, // 类型：0:普通字段 1:公式字段
          hideTag: i.hideTag || 0,
          uniqueFlag: i.uniqueFlag || 0
        };
        if (i.fieldType === 1) {
          obj.fieldName = obj.columnName;
          let tagFormula = '';
          const formulaVariable = [];
          if (i.formulaOrigin && i.formulaOrigin.length > 0) {
            i.formulaOrigin.forEach(j => {
              if (j.type === 'var') {
                const varObj = {
                  name: j.fieldName,
                  fieldName: j.fieldName,
                  columnName: j.columnName,
                  fieldId: j.fieldId
                };
                formulaVariable.push(varObj);
                tagFormula = tagFormula + '#' + j.columnName + '#';
              } else {
                tagFormula = tagFormula + j.tagName;
              }
              const notDelete = ['fieldName', 'fieldId', 'type', 'name', 'columnName', 'tagName'];
              for (const key in j) {
                if (!notDelete.includes(key)) {
                  delete j[key];
                }
              }
            });
          }
          obj.formulaVariable = formulaVariable; // 公式中的变量
          obj.tagFormula = tagFormula; // 公式
          obj.unit = i.unit || ''; // 单位
          obj.formulaOrigin = i.formulaOrigin ? JSON.stringify(i.formulaOrigin) : '';
        }
        return obj;
      }).filter(i => {
        return i.fieldType || !!i.fieldId;
      });
      const repeatName = [];
      selectFieldParams.forEach(i => {
        if (repeatName.includes(i.columnName)) {
          error = '列名称不能重复';
        }
        if (!i.columnName) {
          error = '选取字段中列名称未填写';
        } else {
          repeatName.push(i.columnName);
        }
      });
      if (mustField.fieldId === '') {
        error = '请选取关联字段';
      }
      return { data: selectFieldParams, error };
    },
    // 获取报表筛选相关下拉选项
    async getOpt() {
      const collectOptions = this.collectOptions;
      if (collectOptions && collectOptions.conditionOptions) {
        this.conditionOptions = collectOptions.conditionOptions.condition;
        this.mathOperationOptions = collectOptions.conditionOptions.mathOptions;
      } else {
        try {
          const res = await getOptions();
          if (res.data) {
            this.conditionOptions = res.data.conditionOptions.condition;
            this.mathOperationOptions = res.data.conditionOptions.mathOptions;
          }
        } catch (error) {
          console.error(error);
        }
      }
    },
    // 选择统计报表逻辑
    isReportField(id) {
      const item = this.fieldList.find(i => i.id === id);
      return id === -1 || (item && item.name === '统计报表');
    },
    getRemoteReport() {
      const a = function(params) {
        return new Promise((resolve, reject) => {
          params.reportName = '';
          params.isCreateChart = true;
          params.notShowNoAuthTip = 1;
          if (params.userName) params.reportName = params.userName;
          getReportList(params).then(res => {
            resolve(res);
          }).catch(err => {
            reject(err);
          });
        });
      };
      return a;
    },
    async getReportFieldFun(id, item, isChange) {
      if (!item.reportId) {
        this.$set(item, 'fieldChidrenList', []);
        this.$set(item, 'fieldId', '');
        this.$forceUpdate();
        return;
      }
      if (isChange) item.fieldId = '';
      const params = {
        reportId: item.reportId
      };
      const res = await getReportField(params);
      if (res.data) {
        this.$set(item, 'fieldChidrenList', res.data);
        this.$forceUpdate();
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.select-field {
  .filter-item {
    display: flex;
    align-items: center;
    margin-bottom: 24px;
    position: relative;
    &:last-child {
      margin-bottom: 0;
    }
    .input-container {
      width: 120px;
      margin-right: 12px;
      &::v-deep {
        .el-input__inner {
          width: 120px;
        }
      }
    }
    .add-btn {
      margin-left: 16px;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 30px;
      height: 30px;
      cursor: pointer;
      border-radius:4px;
      background-color: #EFF3FB;
      img {
        width: 16px;
        height: 16px;
      }
    }
    .delete-btn {
      margin-left: 5px;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 30px;
      height: 30px;
      cursor: pointer;
      .delete-icon {
        font-size: 16px;
        color: #6C6C6C;
      }
    }
    .mustField-item {
      margin-left: 10px;
    }
  }
  & ::v-deep {
    .width120 {
      .el-input__inner {
        width: 120px !important;
      }
    }
    .width160 {
      .el-input__inner {
        width: 160px !important;
      }
    }
  }
  .tip-word {
    font-size:14px;
    font-family:PingFangSC-Regular,PingFang SC;
    font-weight:400;
    color:rgba(153,153,153,1);
    line-height:14px;
    margin: 0 7px;
  }
  .el-form-item {
    margin-bottom: 0;
  }
  .index-icon {
    font-size: 16px;
    cursor: pointer;
    color: #406eff;
    margin-right: 10px;
  }
  .eye-icon {
    font-size: 16px;
    cursor: pointer;
    color: #406eff;
    margin-right: 10px;
  }
  .formula-container {
    min-width:616px;
    display: inline-block;
    border-radius:4px;
    border:1px solid #DCDFE6;
    padding: 20px 20px 20px 28px;
  }
  .tool-bar {
    display: flex;
    align-items:center;
    &.float {
      position: absolute;
      top: 0;
      left: 130px;
    }
    img {
      cursor: pointer;
      width: 16px;
    }
  }
}
</style>
